<!--  -->
<template>
  <div class="page-main">
    <CustomForm
      :formInline="formInline"
      @onSubmit="onSubmit"
      @resetTable="resetTable"
      :exportBtn="true"
      @exportHandler="exportHandler"
      :tooltipContent="'导出数据之前需要先选择时间'"
    >
      <el-form-item label="总运单">
        <el-input v-model="formInline.add_id" placeholder="请输入总运单"></el-input>
      </el-form-item>
      <el-form-item label="分运单">
        <el-input v-model="formInline.fyd" placeholder="请输入分运单"></el-input>
      </el-form-item>
      <el-form-item label="代开审核">
        <el-select v-model="formInline.dksh" placeholder="选择审核状态" @change="changeStatusSelect">
          <el-option label="全部" :value="0"></el-option>
          <el-option label="未审核" :value="1"></el-option>
          <el-option label="通过" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="代开状态">
        <el-select v-model="formInline.dkzk" placeholder="选择审核状态" @change="changeStatusSelect">
          <el-option label="全部" :value="0"></el-option>
          <el-option label="待申请" :value="1"></el-option>
          <el-option label="已申请" :value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="时间">
        <el-date-picker
          v-model="pickerDateArr"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="changeDatePicker"
          clearable
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="司机姓名">
        <el-input v-model="formInline.sjxm" placeholder="请输入姓名"></el-input>
      </el-form-item>

      <el-form-item label="车牌号">
        <el-input v-model="formInline.cph" placeholder="请输入车牌号"></el-input>
      </el-form-item>
      <el-form-item label="所属地区">
        <el-select v-model="formInline.area_status" placeholder="选择所属公司" @change="selectArea">
          <el-option label="全部" :value="-1"></el-option>
          <el-option
            v-for="(item, index) in getOfficesList"
            :key="item"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
    </CustomForm>
    <div class="btns-box">
      <download-excel
        ref="downloadexcel"
        :data="exportData"
        :fields="fields"
        :header="exportHeader"
        :name="exportName"
        :worksheet="exportSheet"
        :footer="exportFooter"
        :defaultValue="exportDefaultValue"
      >
        <span></span>
        <!-- <el-button type="primary" style="position: absolute;left: 0;">勾选导出</el-button> -->
      </download-excel>

      <el-button type="primary" style="position: absolute;left: 0;" @click="selectExport">勾选导出</el-button>

      <div class="content">
        <el-button type="primary" @click="batchHandler('12')">批量修改税款所属期</el-button>
        <el-button type="primary" @click="batchHandler('13')">批量审核通过</el-button>
        <el-button type="danger" @click="batchHandler('14')">批量审核不通过</el-button>
        <el-button type="primary" @click="batchHandler('11')">批量申请代开</el-button>
      </div>
    </div>
    <CustomDescriptions
      :data="descriptionsData"
      :styleBox="{ width: '100%', 'margin-top': '12px' }"
    ></CustomDescriptions>

    <el-table
      :data="list"
      style="width: 100%"
      height="530"
      v-loading="tableloading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column
        prop="area_company"
        label="所属地区"
        width="100"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="yund_id"
        label="运单ID"
        width="120"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">{{ scope.row.add_id + '-' + scope.row.yund_id }}</template>
      </el-table-column>
      <el-table-column
        prop="driver_name"
        label="司机姓名"
        width="100"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">{{ $maskString(scope.row.driver_name) }}</template>
      </el-table-column>
      <el-table-column prop="sfz" label="身份证号" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column
        prop="cph"
        label="车牌号"
        width="110"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="ship_address"
        label="装货地址"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column prop="to_address" label="收货地址" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="goods" label="货物名称" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="zyf" label="劳务金额" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="stime" label="税款所属期" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="add_time" label="开始时间" align="center" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="dksh" label="代开审核" align="center" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.dksh == 0" style="color:red">未审核</span>
          <span v-else-if="scope.row.dksh == 1" style="color:green">已审核</span>
        </template>
      </el-table-column>

      <el-table-column prop="dkzk" label="代开状态" align="center" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.dkzk == 0" style="color:red">待申请</span>
          <span v-else-if="scope.row.dkzk == 1" style="color:green">已申请</span>
        </template>
      </el-table-column>

      <!-- <el-table-column prop="is_upload_pay" label="上传支付凭证" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.is_upload_pay == 0" style="color:red">未上传</span>
                    <span v-else-if="scope.row.is_upload_pay == 1" style="color:green">已上传</span>
                </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" width="120">
        <!-- <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="showUploadPay(scope.row)">上传支付截图</el-button>
        </template>-->
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="formInline.page"
      :page-sizes="[10, 20, 30, 50, 80, 100, 200, 300]"
      :page-size="formInline.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog
      title="请选择税款所属期"
      :visible.sync="batchTimeDialog"
      width="30%"
      center
      custom-class="tax-dialog"
    >
      <el-date-picker
        v-model="batchForm.stime"
        type="month"
        placeholder="选择日期"
        value-format="yyyy-MM"
        :picker-options="pickerOptions"
      ></el-date-picker>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchTimeDialog = false">取 消</el-button>
        <el-button type="primary" @click="batchTimeHandler">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="上传支付截图" :visible.sync="payDialog" width="50%">
      <div class="block">
        <div class="demonstration">支付凭证：</div>
        <uploadImgPrev :textType="'pay'" @getImageList="getImageList" :imageList="[pay_img]"></uploadImgPrev>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="payDialog = false">取 消</el-button>
        <el-button type="primary" @click="updatePayImgHandle">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { summary, batchModification, uploadPayImg } from "@/api/childCompany/moneyManagment";
import uploadImgPrev from "@/components/uploadImgPrev/index.vue";
import {
  getDaysInCurrentMonth,
  convertObjectToQueryString
} from "@/utils/tool";
import { getOfficesList, getToken, getUserId } from "@/utils/auth";
import vueJsonExcelUmd from "@/utils/vue-json-excel";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    uploadImgPrev,
    downloadExcel: vueJsonExcelUmd
  },
  data() {
    //这里存放数据
    return {
      //勾选导出相关数据
      fields: {
        司机姓名: "driver_name",
        司机身份证: "sfz",
        运单号: "yund_id",
        车牌号码: "cph",
        装货地址: "start_address",
        收货地址: "to_address",
        货物名称: "goods",
        运输劳务金额: "zyf",
        税款所属期: "stime",
        代开审核: "dkzk",
        代开状态: "dksh"
      },
      exportName: "汇总代开",
      exportSheet: "汇总代开",
      exportHeader: "",
      exportFooter: "",
      exportDefaultValue: "",
      // 导出表格数据
      exportData: [],

      getOfficesList: getOfficesList(),
      formInline: {
        sjxm: "",
        dkzk: 0, //0全部1待申请2已申请
        dksh: 0, //代开审核0全部1待申请2通过
        time: "",
        add_id: "", //总运单id
        cph: "",
        fyd: "",
        page: 1,
        pageSize: 10,
        area_status: 0 //例如:0 安阳总公司
      },
      pickerDateArr: "",
      list: [],
      descriptionsData: [
        {
          label: "运单总重量",
          count: 0,
          unit: "(吨)"
        },
        {
          label: "劳务金额",
          count: 0,
          unit: "(元)"
        }
      ],
      total: 0,
      tableloading: false,

      multipleSelection: [],

      batchForm: {
        ids: "",
        type: "", //11 代开申请 12 批量修改税款所属期 13 批量审核通过 14 批量审核拒绝
        stime: "" //type = 12 为必传值 时间
      },
      batchTimeDialog: false,

      taxTime: "", //修改税款所属期时间
      payDialog: false,

      pay_img: "", //上传支付图片URL
      payImgId: "", //上传支付图片所需ID
      pickerOptions: {
        disabledDate(time) {
          const currentDate = new Date();
          const currentMonth = currentDate.getMonth();
          const currentYear = currentDate.getFullYear();

          if (time.getFullYear() > currentYear) {
            return true;
          } else if (
            time.getMonth() > currentMonth &&
            time.getFullYear() === currentYear
          ) {
            return true;
          }
          return false;
        }
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async summary() {
      this.tableloading = true;
      let res = await summary(this.formInline);
      if (res.code == 200) {
        this.list = res.data.list.data;
        this.total = res.data.count;
        this.descriptionsData[0].count = res.data.weight;
        this.descriptionsData[1].count = res.data.money;
      }
      this.tableloading = false;
    },
    onSubmit() {
      // console.log(this.formInline);
      this.formInline.page = 1;
      this.summary();
    },
    resetTable() {
      this.formInline = {
        sjxm: "",
        dkzk: 0, //0全部1待申请2已申请
        dksh: 0, //代开审核0全部1待申请2通过
        time: "",
        add_id: "", //总运单id
        cph: "",
        fyd: "",
        page: 1,
        pageSize: 10,
        area_status: 0
      };
      this.multipleSelection = [];
      this.pickerDateArr = "";
      this.summary();
    },
    changeDatePicker(data) {
      if (data) {
        // data[1].splice(-2, 2, getDaysInCurrentMonth())
        // data[1].
        let data1 = [...data];
        let newStr = data[1].slice(0, data[1].length - 2);
        newStr += getDaysInCurrentMonth();
        data1[1] = newStr;
        this.formInline.time = data1.join(" - ");
      } else {
        this.formInline.time = "";
      }
    },
    showUploadPay(row) {
      this.pay_img = row.pay_img;
      this.payImgId = row.id;
      this.payDialog = true;
    },
    handleCurrentChange(page) {
      this.formInline.page = page;
      this.summary();
    },
    handleSizeChange(pageSize) {
      this.formInline.pageSize = pageSize;
      this.summary();
    },
    handleSelectionChange(val) {
      //选中的 selection 数组
      if (val) {
        this.multipleSelection = val;
        this.batchForm.ids = val.reduce((prev, curr, index) => {
          return prev + curr.id + (val.length - 1 == index ? "" : ",");
        }, "");
      } else {
        this.batchForm.ids = "";
      }
    },
    changeStatusSelect() {
      this.summary();
    },
    async batchHandler(type) {
      if (!this.batchForm.ids) {
        this.$message.error("请先选择数据!");
      } else {
        if (type == 12) {
          this.batchTimeDialog = true;
          return;
        }
        if (type == 11) {
          if (
            this.formInline.area_status !== 0 &&
            this.multipleSelection.some(item => {
              return item.is_upload_pay == 0;
            })
          ) {
            this.$message.error("所选数据中包含未上传支付凭证订单!");
            return;
          }

          if (
            this.multipleSelection.some(item => {
              return item.dkzk == 1;
            })
          ) {
            this.$message.error("所选数据中包含已申请代开!");
            return;
          }
        }
        let arrTextInfo = {
          "11": {
            label1: "确实要把这些运单进行代开申请吗？（代开后不可恢复！）",
            label2: "代开申请"
          },
          "13": {
            label1: "确实要把这些运单审核通过？",
            label2: "审核代开"
          },
          "14": {
            label1: "确实要把这些运单审核不通过？",
            label2: "审核代开"
          }
        };
        this.$confirm(arrTextInfo[type].label1, arrTextInfo[type].label2, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            this.batchForm.type = type;
            let res = await batchModification(this.batchForm);
            if (res.code == 200) {
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
            this.summary();
          })
          .catch(() => {});
      }
    },
    async batchTimeHandler() {
      if (!this.batchForm.stime) {
        this.$message.error("请选择修改税款所属日期");
        return;
      }
      this.batchForm.type = "12";
      let res = await batchModification(this.batchForm);
      if (res.code == 200) {
        this.$message.success(res.msg);
        this.summary();
      } else {
        this.$message.error(res.msg);
      }

      this.batchTimeDialog = false;
    },
    getImageList(list, index) {
      if (list[0].name == "pay") {
        this.pay_img = list[0].url;
      }
    },
    async updatePayImgHandle() {
      let res = await uploadPayImg({
        id: this.payImgId,
        pay_img: this.pay_img
      });
      if (res.code == 200) {
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.msg);
      }
      this.payDialog = false;
      this.summary();
    },
    selectArea() {
      this.summary();
    },
    exportHandler() {
      //导出数据
      console.log(this.formInline);
      if (!this.formInline.time) {
        this.$message.error("请先选择时间段!");
        return;
      }
      let newStr = convertObjectToQueryString(this.formInline);
      window.open(
        `https://api.zhgylgl.com/api/admin/summaryExprot?&${newStr}&token=${getToken()}&userId=${getUserId()}`,
        "_blank",
        ""
      );
    },
    selectExport() {
      //勾选导出
      if (!this.multipleSelection.length) {
        this.$message.error("请先勾选导出的数据!");
        return;
      }
      this.exportData = this.multipleSelection.map(item => {
        return {
          driver_name: item.driver_name,
          sfz: item.sfz_display,
          yund_id: item.yund_id,
          cph: item.cph,
          start_address: item.ship_code,
          to_address: item.to_code,
          goods: item.goods,
          zyf: item.zyf,
          stime: item.stime,
          dkzk: item.dkzk == 0 ? "未申请" : "已申请",
          dksh: item.dksh == 0 ? "未审核" : "已审核"
        };
      });
      this.$nextTick(() => {
        //手动触发下载事件
        this.$refs.downloadexcel.$el.click();
      });

      return;

      const yund_ids = this.multipleSelection.reduce((prev, curr, index) => {
        return (
          prev +
          curr.yund_id +
          (this.multipleSelection.length - 1 == index ? "" : ",")
        );
      }, "");
      window.open(
        `https://api.zhgylgl.com/api/admin/summarySingleExprot?&yund_id=${yund_ids}&token=${getToken()}&userId=${getUserId()}`,
        "_blank",
        ""
      );
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.summary();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
::v-deep .el-pagination {
  margin-top: 5px;
}

.btns-box {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 40px;
  position: relative;

  .content {
    width: 40%;
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
}

::v-deep .tax-dialog {
  .el-dialog__body {
    display: flex;
    justify-content: center;

    .el-date-editor.el-input {
      width: 60%;
    }
  }
}

::v-deep .el-date-editor--monthrange {
  width: auto;

  .el-range-separator {
    width: 10%;
  }
}

.block {
  display: flex;
  padding: 30px;
  width: 40%;
  height: 300px;
  overflow: hidden;
}

.demonstration {
  width: 30%;
}

// ::v-deep .el-table .el-table__cell {
//     padding: 10px 0;

//     .cell {
//         padding-left: 2px;
//         padding-right: 2px;
//     }
// }

::v-deep .el-pagination {
  margin-top: 20px;
}
</style>